import Label from "./FormLabel";
import FormGroup from "./FormGroup";
import FormItem from "./FormItem";
import InputGroup from "./InputGroup";
import UploadThub from "./UploadThub/index";
import FormItemType from "./FormItemType";
import Editor from "./editor";
import Star from "./Star";
import Modal from "./Modal/";
import SingleSelectClass from "./form/single_select_class";
import Selected from "./SelectItem";
import DatePicker from 'react-datepicker';


export default React.createClass({
    getInitialState(){
        return {
            startDate: Moment(),
            list: [],
        }
    },
    propsType: {
        form: React.PropTypes.array
    },
    componentWillReceiveProps(nextProps){
        if (_.isArray(nextProps['form'])) {
            this.setState({list: nextProps['form']});
        } else {
            throw  new Error('invalid argument !')
        }
    },
    getDefaultProps(){
        return {};
    },
    handleChange(index, value){
        if (!this.state.list.length) {
            this.setState({
                list: this.props.form
            }, function () {
                this.change(index, value);
            })
        } else {
            this.change(index, value);
        }

    },
    change(index, value){
        let item = this.state.list[index], tips = '';

        //规则校验
        if (item.required) {
            if (!value.length) {
                tips = '该项必填!';
            } else {
                if (item.verify && item.verify.length) {
                    for (var i = 0; i < item.verify.length; i++) {
                        if (!item.verify[i].test(value)) {
                            tips = item.verify[i].tips;
                            break;
                        }
                    }
                }
            }
        }
        this.updateItem(index, {
            value: value,
            tips: tips
        })
    },
    updateItem(index, item_, cb){
        let item = this.state.list[index], tips = '';
        this.setState({
            list: [...this.state.list.slice(0, index), Object.assign({}, item, item_),
                ...this.state.list.slice(index + 1)]
        }, cb && cb);
    },
    onSubmit(){
        let valid = true, tips = {msg: {}, index: -1}, self = this;
        for (var i = 0; i < this.state.list.length; i++) {
            let item = this.state.list[i];
            if (item.required) {
                if (!item.value.length) {
                    tips.index = i;
                    tips.msg = {tips: '该项必填!'};
                    break;
                } else {
                    if (item.verify && item.verify.length) {
                        for (var ij = 0; ij < item.verify.length; ij++) {
                            if (!item.verify[ij].test(item.value)) {
                                tips.index = i;
                                tips.msg = {tips: item.verify[ij].tips};
                                break;
                            }
                        }
                    }
                }
            }
        }
        if (tips.index > -1) {
            self.updateItem(tips.index, tips.msg);
        } else {
            this.props.onsubmit(this.state.list);
        }
    },
    handleDateChange(date){

    },

    render(){
        const self = this;
        var list = this.state.list.length > 0 ? this.state.list : this.props.form;
        return <div>
            {
                list.map((item, index)=> {

                    if (item.type == FormItemType.MODAL_CHECK_BOX) {
                        return <FormItem {...item} key={index}>
                            <div className="homeword">
                                {
                                    this.props._user['class'].map((item_, idex)=> {
                                        item_.checked = self.state.list[index].value.indexOf(item_.teachid) > -1;
                                        return <Selected onremove={()=> {
                                            return this.updateItem(index, {
                                                value: item.value.replace(item_.teachid + ',', '')
                                            });
                                        }} key={idex} {...item_} />
                                    })
                                }
                                <button className="btn btn-default btn-sm " onClick={()=> {
                                    this.updateItem(index, {open: true})
                                }} type="button">
                                    <i className="fa fa-hand-o-up"></i> 推送班级
                                </button>
                            </div>
                            <Modal open={item.open}>
                                <Modal.Header onclose={()=> {
                                    this.updateItem(index, {
                                        selected: '',
                                        open: false
                                    });
                                }}>选择</Modal.Header>
                                <Modal.Body>
                                    {
                                        this.props._user['class'].map((item_, idex)=> {
                                            return (
                                                <label className="checkbox-inline" key={idex}>
                                                    <input type="checkbox"
                                                           checked={item.value.concat(item.selected).indexOf(item_.teachid) > -1}
                                                           onClick={(e)=> {
                                                               if (e.target.checked) {
                                                                   this.updateItem(index, {
                                                                       selected: (item.selected ? item.selected : '')
                                                                       + item_.teachid + ','
                                                                   });
                                                               } else {
                                                                   this.updateItem(index, {
                                                                       selected: item.selected.replace(item_.teachid + ',', '')
                                                                   });
                                                               }
                                                           }}/>
                                                    {item_.class.name} </label>
                                            )
                                        })
                                    }
                                </Modal.Body>
                                <Modal.Footer
                                    onclose={()=> {
                                        this.updateItem(index, {
                                            open: false,
                                            selected: '',
                                        });
                                    }}
                                    onconfirm={()=> {
                                        let selected = item.selected;
                                        this.updateItem(index, {
                                            open: false,
                                            value: _.union(item.value.length ? item.value.split(',') : [], selected.split(',')).join(','),
                                            selected: ''
                                        });
                                    }}
                                />
                            </Modal>
                        </FormItem>
                    }

                    return <FormGroup addRow={this.props.addRow} key={index}
                                      className={(item.tips && item.tips.length) ? 'has-error' : ''}>
                        <Label labelAlign={this.props.labelAlign}>
                            { item.required ? <Star></Star> : ''}{item.label}{this.props.addM ? ':' : ''}</Label>
                        <InputGroup textWidth={this.props.textWidth}>
                            {
                                ((item.type == FormItemType.INPUT) || !item.type) ?
                                    <input name={item.name}
                                           className="form-control"
                                           type="text"
                                           onChange={(e)=> {
                                               this.handleChange(index, e.target.value);
                                           }}
                                           ref={item.name}
                                           value={item.value }
                                           placeholder={item.placeholder}/>
                                    : ''
                            }
                            {
                                ((item.type == FormItemType.PASSWORD) ) ?
                                    <input name={item.name}
                                           className="form-control"
                                           type="password"
                                           onChange={(e)=> {
                                               this.handleChange(index, e.target.value);
                                           }}
                                           ref={item.name}
                                           value={item.value }
                                           placeholder={item.placeholder}/>
                                    : ''
                            }

                            {
                                item.type == FormItemType.TEXT_SHOW ?
                                    <p className="form-control form-control-text">{item.value}</p>
                                    : ''
                            }
                            {
                                item.type == FormItemType.TEXT_AREA ?
                                    <textarea name={item.name}
                                              cols="30"
                                              rows="10"
                                              className="form-control"
                                              onChange={(e)=> {
                                                  this.handleChange(index, e.target.value)
                                              }}
                                              defaultValue={item.value}
                                              ref={item.name}
                                              placeholder={this.props.placeholder}></textarea>
                                    : ''
                            }
                            {
                                this.props.type == FormItemType.DATE ?
                                    <div>
                                        <DatePicker
                                            selected={this.state.startDate}
                                            locale="en-gb"
                                            onChange={(date)=> {
                                                debugger;
                                                console.log(date);
                                                this.handleChange(index, date);
                                                this.setState({
                                                    startDate: date
                                                })
                                            }
                                            }/>
                                    </div> : ''
                            }
                            {
                                item.type == FormItemType.UPLOAD ?
                                    <UploadThub onsuccess={(result)=> {
                                        this.handleChange(index, result)
                                    }}></UploadThub>
                                    : ''
                            }
                            {item.type == FormItemType.TEXT_SHOW ? '' :
                                <p className="help-block">{item.tips}</p>}
                        </InputGroup>
                    </FormGroup>
                })
            }
            <FormGroup>
                <Label></Label>
                <InputGroup>
                    <button className={"btn btn-success"}
                            onClick={()=> {
                                if (this.props.editing) {
                                    this.onSubmit();
                                } else {
                                    this.onSubmit();
                                }
                            }}
                            type="submit">
                        {this.props.editing ? this.props.label || '编辑' : this.props.label || '保存'}
                    </button>
                </InputGroup>
            </FormGroup>
        </div>;
    }
});